<template>
  <div class="camera-app">
    <h1>拍照功能演示</h1>
    <video ref="video" width="320" height="240" autoplay></video>
    <canvas ref="canvas" style="display:none;"></canvas>
    <img :src="photo" alt="Taken photo" v-if="photo" />
    <button @click="startCamera" :disabled="isCameraActive">打开摄像头</button>
    <button @click="takePhoto" :disabled="!isCameraActive">拍照</button>
    <button @click="closeCamera" :disabled="!isCameraActive">关闭摄像头</button>
  </div>
</template>

<script>
export default {
  name: 'Camera1',
  data() {
    return {
      stream: null,
      photo: '',
      isCameraActive: false,
    };
  },
  methods: {
    async startCamera() {
      try {
        this.stream = await navigator.mediaDevices.getUserMedia({ video: true });
        const video = this.$refs.video;
        video.srcObject = this.stream;
        this.isCameraActive = true;
      } catch (error) {
        console.error('Error accessing the camera:', error);
      }
    },
    takePhoto() {
      const canvas = this.$refs.canvas;
      const video = this.$refs.video;
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
      this.photo = canvas.toDataURL('image/png');

    },
    closeCamera() {
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null;
        this.isCameraActive = false;
        this.photo = '';
      }
    },
  },
};
</script>

<style scoped>
.camera-app {
  text-align: center;
}
video, img {
  margin-top: 20px;
}
button {
  margin: 5px;
}
</style>
